import json

from django.core import serializers
from django.db.models import Q
from django.http import HttpResponse, QueryDict

from python_web.model.models import PublicServant
from python_web.utils.responseModel import ResponseModel


def index(request):
    # work_site=&gender_requirements=&educational_requirements=研究生&political_outlook=不限&major=
    data = PublicServant.objects.all()
    # data = PublicServant.objects.all().filter(headline)[:800]

    gender_requirements_val = ""
    educational_requirements_val = ""
    political_outlook_val = ""
    work_site_val = ""
    position_code_val = ""

    college_requirements_val = ""
    undergraduate_requirements_val = ""
    graduate_requirements_val = ""

    for key in request.GET.keys():
        value = request.GET[key].strip()
        if key == "gender_requirements":
            gender_requirements_val = value
        if key == "educational_requirements":
            educational_requirements_val = value
        if key == "political_outlook":
            political_outlook_val = value
        if key == "work_site":
            work_site_val = value
        if key == "major":
            college_requirements_val = value
            undergraduate_requirements_val = value
            graduate_requirements_val = value
        if key == "position_code":
            position_code_val = value

    data = data.filter(
        (Q(gender_requirements__startswith=gender_requirements_val))
        & Q(educational_requirements__contains=educational_requirements_val)
        & (Q(political_outlook__startswith=political_outlook_val))
        & Q(work_site__startswith=work_site_val)
        & Q(position_code__contains=position_code_val)
        & (Q(college_requirements__contains=college_requirements_val) | Q(
            undergraduate_requirements__contains=undergraduate_requirements_val) | Q(
            graduate_requirements__contains=graduate_requirements_val))
    )

    result = serializers.serialize("json", data[:300])
    resp = ResponseModel('200', json.loads(result), 'message')
    return HttpResponse(json.dumps(resp.__dict__))
